/**
 * 设备管理API接口模块
 * 
 * 核心功能：
 * - 设备CRUD操作接口
 * - 文件上传接口
 * - 模拟数据接口
 * 
 * 最小实现调用方式：
 * import * as deviceApi from '@/api/device'
 * const devices = await deviceApi.getDevices()
 */

import axios from 'axios'
import { mockDevices as originalMockDevices, mockClickableAreas } from '@/mock/devices'

// 是否使用模拟数据（开发环境默认使用）
const USE_MOCK = import.meta.env.DEV || !import.meta.env.VITE_API_BASE_URL

// 创建可修改的模拟数据副本
let mockDevices = [...originalMockDevices]

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log(`API请求: ${config.method?.toUpperCase()} ${config.url}`)
    return config
  },
  (error) => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log(`API响应: ${response.status} ${response.config.url}`)
    return response
  },
  (error) => {
    console.error('API响应错误:', error.response?.status, error.message)
    return Promise.reject(error)
  }
)

/**
 * 获取设备列表
 */
export const getDevices = () => {
  if (USE_MOCK) {
    console.log('使用模拟数据获取设备列表')
    return Promise.resolve({ data: mockDevices })
  }
  return api.get('/devices')
}

/**
 * 获取单个设备详情
 */
export const getDevice = (deviceId) => {
  if (USE_MOCK) {
    console.log('使用模拟数据获取设备详情:', deviceId)
    const device = mockDevices.find(d => d.id === deviceId)
    return Promise.resolve({ data: device })
  }
  return api.get(`/devices/${deviceId}`)
}

/**
 * 创建设备
 */
export const createDevice = (deviceData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据创建设备:', deviceData.name, '类型:', deviceData.deviceType)
    
    // 创建新设备对象
    const newDevice = {
      id: `device_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      name: deviceData.name,
      description: deviceData.description || '',
      type: 'device',
      category: deviceData.category || 'emergency_life_support',
      status: deviceData.status || 'active',
      deviceType: deviceData.deviceType,
      parentId: null, // 将由store层决定具体的父级关系
      imageCount: deviceData.images?.length || 0,
      thumbnail: deviceData.images?.[0]?.url || deviceData.images?.[0]?.thumbnail || null,
      images: deviceData.images || [],
      coordinateLog: deviceData.coordinateLog || null,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    // 检查是否已存在相同名称的设备（在同一类型下）
    const checkDuplicateName = (devices, name, deviceType) => {
      for (const device of devices) {
        if (device.isCategory && device.children) {
          for (const child of device.children) {
            if (child.name === deviceType && child.children) {
              const duplicate = child.children.find(subChild => subChild.name === name)
              if (duplicate) return true
            }
          }
        } else if (device.name === name && device.deviceType === deviceType) {
          return true
        }
      }
      return false
    }
    
    if (checkDuplicateName(mockDevices, deviceData.name, deviceData.deviceType)) {
      return Promise.reject(new Error(`在${deviceData.deviceType}类型下已存在名为"${deviceData.name}"的设备`))
    }
    
    // 模拟异步操作
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('模拟创建设备成功:', newDevice.name)
        resolve({ data: newDevice })
      }, 500)
    })
  }
  return api.post('/devices', deviceData)
}

/**
 * 更新设备 - 支持嵌套结构更新
 */
export const updateDevice = (deviceId, deviceData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据更新设备:', deviceId)
    
    // 查找设备（支持嵌套结构）
    let deviceFound = false
    let deviceInfo = null
    
    // 遍历所有设备，查找要更新的设备
    for (let i = 0; i < mockDevices.length; i++) {
      const device = mockDevices[i]
      
      // 检查是否是顶级设备
      if (device.id === deviceId) {
        deviceInfo = { type: 'top-level', device: device, index: i }
        deviceFound = true
        break
      }
      
      // 检查是否是嵌套设备（在children中）
      if (device.children && Array.isArray(device.children)) {
        for (let j = 0; j < device.children.length; j++) {
          const childDevice = device.children[j]
          if (childDevice.id === deviceId) {
            deviceInfo = { 
              type: 'nested', 
              device: childDevice, 
              parent: device, 
              parentIndex: i, 
              childIndex: j 
            }
            deviceFound = true
            break
          }
        }
      }
      
      if (deviceFound) break
    }
    
    if (!deviceFound) {
      return Promise.reject(new Error('设备不存在'))
    }
    
    // 构建更新后的设备数据
    const updatedDevice = {
      ...deviceInfo.device,
      ...deviceData,
      imageCount: deviceData.images?.length || deviceInfo.device.imageCount,
      thumbnail: deviceData.images?.[0]?.url || deviceData.images?.[0]?.thumbnail || deviceInfo.device.thumbnail,
      updatedAt: new Date().toISOString()
    }
    
    // 模拟异步操作
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('API层更新设备:', deviceInfo.type, deviceInfo.device.name, '到', updatedDevice.name)
        
        // 根据设备类型执行更新操作
        if (deviceInfo.type === 'top-level') {
          // 更新顶级设备
          mockDevices[deviceInfo.index] = updatedDevice
          console.log('API层更新顶级设备:', updatedDevice.name)
        } else if (deviceInfo.type === 'nested') {
          // 更新嵌套设备
          const parent = deviceInfo.parent
          
          console.log('API层更新嵌套设备:', parent.name, '->', updatedDevice.name)
          
          // 更新子设备数据
          parent.children[deviceInfo.childIndex] = updatedDevice
          
          // 重新计算父设备的统计信息
          let totalImageCount = 0
          let firstThumbnail = null
          
          parent.children.forEach(child => {
            if (child.imageCount) {
              totalImageCount += child.imageCount
            }
            if (!firstThumbnail && child.thumbnail) {
              firstThumbnail = child.thumbnail
            }
          })
          
          // 更新父设备统计信息
          parent.imageCount = totalImageCount
          if (firstThumbnail) {
            parent.thumbnail = firstThumbnail
          }
          
          console.log('API层嵌套设备更新完成，父设备统计信息已更新')
        }
        
        resolve({ data: updatedDevice })
      }, 500)
    })
  }
  return api.put(`/devices/${deviceId}`, deviceData)
}

/**
 * 删除设备 - 支持嵌套结构删除（简化版，只做验证）
 */
export const deleteDevice = (deviceId) => {
  if (USE_MOCK) {
    console.log('使用模拟数据删除设备:', deviceId)
    
    // API层简化处理，只做基本验证
    // 实际的设备查找和删除由Store层完全负责
    console.log('API层接收删除请求，设备ID:', deviceId)
    
    // 模拟异步操作
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('API层验证删除操作成功，设备ID:', deviceId)
        resolve({ data: { success: true, deviceId: deviceId } })
      }, 300)
    })
  }
  return api.delete(`/devices/${deviceId}`)
}

/**
 * 上传设备图片
 */
export const uploadDeviceImage = (deviceId, imageFile) => {
  const formData = new FormData()
  formData.append('image', imageFile)
  
  return api.post(`/devices/${deviceId}/images`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 上传设备坐标日志文件
 */
export const uploadCoordinateLog = (deviceId, logFile) => {
  const formData = new FormData()
  formData.append('log', logFile)
  
  return api.post(`/devices/${deviceId}/coordinates`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 获取设备模拟数据
 */
export const getSimulationData = (deviceId) => {
  return api.get(`/devices/${deviceId}/simulation`)
}

/**
 * 处理点击事件
 */
export const processClick = (deviceId, clickData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据处理点击事件:', deviceId, clickData)
    const areas = mockClickableAreas[clickData.currentImage] || []
    const clickedArea = areas.find(area => 
      clickData.position.x >= area.x && 
      clickData.position.x <= area.x + area.width &&
      clickData.position.y >= area.y && 
      clickData.position.y <= area.y + area.height
    )
    
    return Promise.resolve({
      data: {
        success: true,
        nextImage: clickedArea?.nextImage || null,
        action: clickedArea?.action || 'unknown'
      }
    })
  }
  return api.post(`/devices/${deviceId}/click`, clickData)
}

/**
 * 获取图片的可点击区域
 */
export const getClickableAreas = (imageId) => {
  if (USE_MOCK) {
    console.log('使用模拟数据获取可点击区域:', imageId)
    return Promise.resolve({ data: mockClickableAreas[imageId] || [] })
  }
  return api.get(`/images/${imageId}/areas`)
}

/**
 * 删除设备图片
 */
export const deleteDeviceImage = (deviceId, imageIndex) => {
  if (USE_MOCK) {
    console.log('API层接收删除图片请求，设备ID:', deviceId, '图片索引:', imageIndex)
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('API层验证删除图片操作成功，设备ID:', deviceId, '图片索引:', imageIndex)
        resolve({ 
          data: { 
            success: true, 
            deviceId: deviceId,
            imageIndex: imageIndex
          } 
        })
      }, 300)
    })
  }
  return api.delete(`/devices/${deviceId}/images/${imageIndex}`)
}

/**
 * 添加设备图片
 */
export const addDeviceImage = (deviceId, imageFile) => {
  if (USE_MOCK) {
    console.log('API层接收添加图片请求，设备ID:', deviceId, '图片文件:', imageFile.name)
    
    return new Promise((resolve) => {
      setTimeout(() => {
        // 创建模拟的图片对象
        const mockImage = {
          id: `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          name: imageFile.name.replace(/\.[^/.]+$/, ""), // 移除文件扩展名
          url: URL.createObjectURL(imageFile), // 创建临时URL用于预览
          thumbnail: URL.createObjectURL(imageFile),
          size: imageFile.size,
          type: imageFile.type,
          uploadTime: new Date().toISOString()
        }
        
        console.log('API层模拟添加图片成功:', mockImage)
        resolve({ 
          data: mockImage
        })
      }, 500)
    })
  }
  
  // 真实环境下的文件上传
  const formData = new FormData()
  formData.append('image', imageFile)
  
  return api.post(`/devices/${deviceId}/images`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
